package net.cachedb4j.dao.support;

import net.cachedb4j.dao.pojo.database.Status;
import net.cachedb4j.exception.database.DatabaseConnectException;
import net.cachedb4j.exception.database.DatabaseMapException;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.jpa.support.JpaDaoSupport;

public abstract class CacheJpaDaoSupport extends JpaDaoSupport {
	
	public CacheDaoSupport cacheSupport;

	public CacheDaoSupport getCacheSupport() {
		return cacheSupport;
	}

	public void setCacheSupport(CacheDaoSupport cacheSupport) {
		this.cacheSupport = cacheSupport;
	}

	public Object persist(Class<?> clazz, Object entity) throws DatabaseConnectException, DatabaseMapException {
		if(! isDatabaseAvailable()) {
			logger.error("Database was losed connection!");
			throw new DatabaseConnectException();
		}

		Object object = null;
		switch (getDatabaseStat()) {
		case BUSY:
			object = getCacheSupport().saveEntity(clazz, entity);
			break;

		default:
			try {
				object = getJpaTemplate().merge(entity);
				if(isNeedStored(clazz, entity)) {
					// TODO store the entity in cache
				}
			} catch(DataAccessException e) {
				// TODO handle exception, how to process
			}
			break;
		}

		return object; 
	}

	//judge the configuration
	private boolean isNeedStored(Class<?> clazz, Object entity) {
		// TODO Auto-generated method stub
		return false;
	}

	private boolean isDatabaseAvailable() {
		// TODO Auto-generated method stub
		return false;
	}

	private Status getDatabaseStat() {
		// TODO Auto-generated method stub
		return Status.BUSY;
	}

}
